package com.springboot.jdk.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: zr
 * @date: 2021-09-30
 */
public class ConditionDemo {

    public static volatile int i = 0;

    private static ReentrantLock lock = new ReentrantLock(true);

    static Condition condition = lock.newCondition();

    public static void main(String[] args) {
        new Thread() {
            @Override
            public void run() {
                // 线程1先获取到锁，但是中间执行业务逻辑的时候，想释放掉锁，等一会儿
                System.out.println("线程1：1、尝试获取锁");
                lock.lock();
                System.out.println("线程1：2、获取锁执行阻塞之前的逻辑");
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程1：3、阻塞之后的业务逻辑");
                lock.unlock();
                System.out.println("线程1：4、释放锁");
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                System.out.println("线程2：1、尝试获取锁");
                lock.lock();
                System.out.println("线程2：2、加锁成功，休眠3秒");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程2：3、唤醒线程1");
                condition.signal();
                lock.unlock();
                System.out.println("线程2：4、释放锁");
            }
        }.start();
    }
}
